<?php


namespace app\api\controller;


use app\api\model\Member;
use think\Loader;
use app\api\model\Rush;
//http://cosmo.com/api/bar/index
class Bar extends BaseApi {

    public function index(){
        Loader::import('barcode/class/BCGColor',EXTEND_PATH);
        Loader::import('barcode/class/BCGFontFile',EXTEND_PATH);
        Loader::import('barcode/class/BCGDrawing',EXTEND_PATH);
        Loader::import('barcode/class/BCGcode39',EXTEND_PATH,'.barcode.php');

        $openid = trim($this->request->param('openid'));
        $discountid = intval($this->request->param('discountid'));
        $rushid = intval($this->request->param('rushid'));

        if($openid){//积分条形码
            $member = new Member();
            $memberItem = $member->getMember($openid);
            $content = $memberItem->creditcode;
        }

        if($discountid){//优惠券条形码
            $userDiscount = new \app\api\model\Userdiscount();
            $userDiscountItem = $userDiscount->getUserDiscount(['id'=>$discountid]);
            $content = $userDiscountItem->verify;
        }

        if($rushid){//抢购订单核销码
            $rush = new Rush();
            $rushItem = $rush->getRush(['id'=>$rushid,'status'=>1],'rushsn');
            if (empty($rushItem)) {
                return json(['code' => -1, 'msg' => '该订单未支付或已删除']);
            }
            $content = $rushItem->rushsn;
        }


        $color_black = new \BCGColor(0, 0, 0);
        $color_white = new \BCGColor(255, 255, 255);
        $drawException = null;

        try
        {
            $code = new \BCGcode39();
            $code->setScale(2);
            $code->setThickness(30); // 条形码的厚度
            $code->setForegroundColor($color_black); // 条形码颜色
            $code->setBackgroundColor($color_white); // 空白间隙颜色
            // $code->setFont($font); //
            $code->parse($content); // 条形码需要的数据内容
        }
        catch(\Exception $exception)
        {
            $drawException = $exception;
        }

        //根据以上条件绘制条形码
        $drawing = new \BCGDrawing('', $color_white);
        if($drawException) {
            $drawing->drawException($drawException);
        }else{
            $drawing->setBarcode($code);
            $drawing->draw();
        }

        // 生成PNG格式的图片
        header('Content-Type: image/png');
        $drawing->finish(\BCGDrawing::IMG_FORMAT_PNG);
    }






}